/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.threadpool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


/**
 *
 * @author vlad
 */
public class ThreadPool {
    
    private final BlockingQueue<Runnable> workerQueue =
            new LinkedBlockingQueue<>();
    private final Thread[] workerThreads;
    
    public ThreadPool(int N)
    {
        workerThreads = new Thread[N];
 
        //Start N Threads and keep them running
        for (int i = 0; i < N; i++) {
            workerThreads[i] = new Worker("Pool Thread " + i, workerQueue);
            //workerThreads[i].start();
        }
    }
    
    public void start() {
        for (int i = 0; i < workerThreads.length; i++) {
            workerThreads[i].start();
        }
    }
 
    public void addTask(Runnable r)
    {
        try {
            workerQueue.put(r);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
 
    public void shutdown()
    {
        while (!workerQueue.isEmpty()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //interruption
            }
        }
        for (Thread workerThread : workerThreads) {
            workerThread.interrupt();
        }
    }
 
    
}
